# -*- coding: utf-8 -*-
"""
Created on Tue Aug 31 12:51:38 2021

@author: hzy
"""
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
from email import encoders
from email.header import make_header
from email.utils import formatdate


# from email.mime.application import MIMEApplication
# from email.mime.image import MIMEImage
# from email.utils import parseaddr, formataddr
# from email.utils import COMMASPACE, formatdate


class MailSender(object):
    _from = None

    def __init__(self, smtpSvr, port):
        self.smtp = smtplib.SMTP_SSL()
        print("connecting...")
        self.smtp.connect(smtpSvr, port)
        print("connected!!!")
        self.attachments = []

    def login(self, user, pwd):
        self._from = user
        print("login ...")
        self.smtp.login(user, pwd)

    def add_attachment(self, file, filename):
        '''
            添加附件
        '''
        att = MIMEBase('application', 'octet-stream')
        att.set_payload(open(file, 'rb').read())
        #        filename=file.split('/')[-1].strip()
        att.add_header('Content-Disposition', 'attachment', fileName="%s" % Header(filename, 'UTF-8').encode('UTF-8'))
        encoders.encode_base64(att)

        self.attachments.append(att)

    def send(self, subject, content, to_addr):
        '''
            发送邮件
        '''
        msg = MIMEMultipart('related')
        contents = MIMEText(content, "html", _charset='utf-8')
        msg['Subject'] = subject
        msg['Date'] = formatdate(localtime=True)
        msg['From'] = self._from
        msg['To'] = to_addr
        for att in self.attachments:
            msg.attach(att)
        msg.attach(contents)
        try:
            self.smtp.sendmail(self._from, to_addr, msg.as_string())
            print("邮件发送成功")
            return True
        except Exception as e:
            print("Error: 无法发送邮件", str(e))
            return False

    def close(self):
        self.smtp.quit()
        print("logout.")


if __name__ == '__main__':
    email = MailSender('smtp.qq.com', 465)

    # 登录邮件
    mail_user = 'xxxxxg@qq.com'  # 用户名
    mail_pass = 'xxxxxy'  # 口令
    email.login(mail_user, mail_pass)

    # 添加附件
    dst_file1 = 'xxxxxxxxxxxx'
    # 自定义文件名or默认
    email.add_attachment(dst_file1, filename='test.xlsx')

    dst_file2 = 'xxxxxxxxxxxx'
    email.add_attachment(dst_file2, filename=dst_file2)

    # 发送邮件+邮件主题+邮件正文
    subject = "test" + ' voltePSBC #@ 指标 alarm ' + time.ctime()
    # 邮件正文
    content = """报警提醒

                   """
    # 收件人
    receivers = 'xxxxxx@qq.com'

    # receivers = ['chenxiaoxiao@js.chinamobile.com','sunyan@js.chinamobile.com','dongxiaohui@js.chinamobile.com','yuanzhouxiang@js.chinamobile.com','sunxb@js.chinamobile.com','tangsb@js.chinamobile.com','chenyansgs1@js.chinamobile.com','xiezh@js.chinamobile.com','taozhipingsgs@js.chinamobile.com','caiweimin@js.chinamobile.com','daicg@js.chinamobile.com','chenchengsgs1@js.chinamobile.com','sunyan@js.chinamobile.com']
    # receivers=','.join(receivers)
    # 发送邮件
    email.send(subject, content, to_addr=receivers)

    # 退出SMTP
    email.close()























